<?php

namespace app\api\controller;

use think\Db;
use app\api\model\ConfigSystem as Config;
use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords;
use app\api\model\User;
use app\api\model\Privatechat;

class Turntable extends Common
{
    public function lists()
    {
        $data = Db::name('turn_table')->field('id, title, icon, money')->order('sort desc, id asc')->select();

        $last_topup = Db::name('topup')->where(['fk_userid'=>$this->member['id'], 'state'=>1])->order('id desc')->find();
        if ($last_topup['price'] != 50) {
            foreach ($data as &$value) {
                if ($value['money'] == 0) continue;
                $value['money'] = round($last_topup['price'] / 50 * $value['money']);
                $value['money'] = $value['money'] > 1 ? $value['money'] : 1;
                $value['title'] = $value['money'] . '金币';
            }
        }

        return $this->pass($data);
    }

    public function config()
    {
        $config = Config::index('', 'topup_reward');

        $data['lottery_count'] = $config['topup_reward'];

        $data['had_count'] = $this->member['lottery_count'];

        return $this->pass($data);
    }

    public function lottery()
    {
        $config = Config::index('', 'topup_reward');

        if (!$this->member['lottery_count']) {
            return $this->miss('没有可使用的抽奖机会');
        }

        $data = Db::name('turn_table')->field('id, probability v')->select();

        $id = getrand($data);

        $reward = Db::name('turn_table')->find($id);

        $last_topup = Db::name('topup')->where(['fk_userid'=>$this->member['id'], 'state'=>1])->order('id desc')->find();
        if ($last_topup['price'] != 50) {
            if ($reward['money'] > 0) {
                $reward['money'] = round($last_topup['price'] / 50 * $reward['money']);
                $reward['money'] = $reward['money'] > 1 ? $reward['money'] : 1;
                $reward['title'] = $reward['money'] . '金币';
            }
        }

        User::where(['id' => $this->member['id']])->setDec('lottery_count');

        $status = 0;
        if ($reward['types'] == 1) {
            if ($reward['money'] + 0) {
                Balance::index($this->member['id'], $reward['money'], '转盘抽奖获得'.$reward['title'], 1);
            }
                $data = ['id' => $reward['id'], 'types' => 1, 'money' => $reward['money']];

                $status = 1;
        } else if (in_array($reward['types'], [2])) {
            $car = Db::name('car')->where(['types' => 1, 'is_hidden' => 0])->orderRaw('rand()')->find();

            if ($car) {
                $user_car = Db::name('user_car')->where(['car_id' => $car['id'], 'user_id' => $this->member['id']])->find();

                if ($user_car) {
                    $time = $user_car['expire'] > time() ? $user_car['expire'] : time();
                    $time += 86400 * 3;
                    Db::name('user_car')->where(['id' => $user_car])->setField('expire', $time);
                } else {
                    Db::name('user_car')->insert([
                        'car_id' => $car['id'],
                        'user_id' => $this->member['id'],
                        'expire' => time() + 86400 * 3,
                        'create_time' => time(),
                        'update_time' => time(),
                    ]);
                }

                $data = ['id' => $reward['id'], 'types' => $reward['types'], 'money' => 0, 'name' => $car['name'], 'cover' => changeUrl($car['cover']), 'msg' => '有效期3天'];

                $status = 1;
            }
        }

        $contain = [
            'user_id' => $this->member['id'],
            'description' => $reward['title'],
            'status' => $status,
            'create_time' => time(),
            'update_time' => time(),
        ];

        $lotteryId = Db::name('user_lottery')->insertGetId($contain);

        if ($status) {
            $data['lottery_id'] = $lotteryId;
            
            //$notice = '恭喜！本次转盘抽奖你抽中了 [' . $reward['title'] . ']';
            //Privatechat::notice($this->member['id'], $notice);

            return $this->pass($data);
        } else {
            return $this->miss('很遗憾，未抽中奖品');
        }
    }
    
    public function lotteryNotice()
    {
        $userLottery = Db::name('user_lottery')->where(['id' => $this->params['lottery_id'], 'user_id' => $this->member['id']])->find();
        
        if ($userLottery && $userLottery['description'] != '谢谢惠顾') {
            $notice = '恭喜！本次转盘抽奖你抽中了 [' . $userLottery['description'] . ']';
            Privatechat::notice($this->member['id'], $notice);
        }
    }

    public function objectlists()
    {
        $data = Db::name('turn_table_of_objects')->field('id,goods_id')->order('sort desc, id asc')->select();
        $goods = Db::name('mall_goods')->where(['id'=>['in', array_column($data, 'goods_id')]])->column('name,image', 'id');
        foreach ($data as $key => $value) {
            $data[$key]['object'] = $goods[$value['goods_id']] ?? ['image'=>'/disk/uploads/image/20220720/5c3beb82429563d843837fe3226e190075f48b2a.png','name'=>'谢谢惠顾'];
        }
        return $this->pass($data);
    }

    public function objectconfig()
    {
        $config = Config::index('', 'turn_of_object');

        return $this->pass('获取成功', 'data', ['data'=>$config['turn_of_object']]);
    }
    public function objectlottery($paymethod = 1)
    {
        $config = Config::index('', 'turn_of_object');
        $price = $config['turn_of_object'];
        $data = Db::name('turn_table_of_objects')->field('id, probability v')->select();
        if (empty($data)) {
            return $this->miss('暂无奖品可抽');
        }

        if ($paymethod == 1) {
            if ($this->member['volley'] < $price) {
                return json(['code'=>201, 'msg'=>'您的金币不足']);
            }
            Balance::index($this->member['id'], $price, '实物转盘抽奖');
        } else {
            if ($this->member['realname_auth'] != 2) {
                return json(['code'=>201, 'msg'=>'未实名认证']);
            }
            $frozen = Db::name('wallet_frozen')->where(['user_id'=>$this->member['id']])->find();
            if($frozen){
                $this->member['score'] = $this->member['score'] - $frozen['value'];
            }
            if ($this->member['score'] < $price) {
                return json(['code'=>201, 'msg'=>'您的积分不足']);
            }
            YaoqingRecords::index($this->member['id'], 0, $price, '实物转盘抽奖', 1, '', 1);
        }


        $id = getrand($data);

        $reward = Db::name('turn_table_of_objects')->find($id);

        $goods = Db::name('mall_goods')->where(['id'=>$reward['goods_id']])->find();

        $timenow = time();

        Db::name('turn_table_of_objects_records')->insertGetId([
            'user_id' => $this->member['id'],
            'type' => $paymethod,
            'price' => $price,
            'goods_id'=>$reward['goods_id'],
            'description' => $goods ? $goods['name'] : '谢谢惠顾',
            'time' => $timenow,
        ]);

        if (!$goods) {
            return json(['code'=>400, 'msg'=>'很遗憾，未抽中奖品', 'id'=>$id]);
        }

        $contain = [
            'user_id' => $this->member['id'],
            'description' => $goods['name'],
            'goods_id'=>$reward['goods_id'],
            'create_time' => $timenow,
            'update_time' => $timenow,
            'expire_time' => $timenow + 30 * 86400
        ];
        $lotteryId = Db::name('user_lottery_of_objects')->insertGetId($contain);


        if ($lotteryId) {
            $notice = '恭喜！本次转盘抽奖你抽中了实物奖品 [' . $goods['name'] . ']，奖品保留30天，请尽快领取';
            Privatechat::notice($this->member['id'], $notice);
            return $this->pass($notice, 'data', ['id'=>$id]);
        } else {
            return json(['code'=>400, 'msg'=>'很遗憾，未抽中奖品', 'id'=>$id]);
        }
    }

    public function lotteryrecords($page = 1, $pagesize = 20)
    {
        $data = Db::name('user_lottery_of_objects')
                    ->where(['user_id'=>$this->member['id']])
                    ->order('create_time desc')
                    ->page($page)
                    ->limit($pagesize)
                    ->select();
        foreach ($data as &$value) {
            $value['create_time'] = date('Y-m-d H:i', $value['create_time']);
            $value['update_time'] = date('Y-m-d H:i', $value['update_time']);
            $value['expire_time'] = date('Y-m-d H:i', $value['expire_time']);
        }
        return $this->pass($data);
    }

    public function receivePrizes($lottery_id = 0, $address_id = 0, $remark = '')
    {
        $reward = Db::name('user_lottery_of_objects')->where(['user_id'=>$this->member['id'], 'id' => $lottery_id])->find();
        if (!$reward) {
            return $this->miss('中奖记录不存在');
        }
        if ($reward['status'] == 1) {
            return $this->miss('奖品已领取');
        }
        if ($reward['status'] == -1) {
            return $this->miss('奖品已过期失效');
        }
        $goods = Db::name('mall_goods')->where(['id'=>$reward['goods_id']])->find();
        if (!$goods) {
            return $this->miss('商品已失效，请联系客服处理');
        }
        $addressInfo = Db::name('mall_member_address')->where(['id' => $address_id, 'uid' => $this->member['id']])->find();
        if (!$addressInfo) return $this->miss('地址选择错误');

        $current_time = time();
        $orderArr = [
            'number' => uniqid('rp'),
            'uid' => $this->member['id'],
            'merchant_id' => $goods['user_id'],
            'gateway' => 255,
            'status' => 1,
            'remark' => $remark,
            'types' => 1,
            'create_time' => $current_time,
            'expire_time' => $current_time + 30 * 60, // 订单有效时间
        ];
        $orderArr['address'] = json_encode([
            'receiver' => $addressInfo['receiver'],
            'mobile' => $addressInfo['mobile'],
            'area' => $addressInfo['area'],
            'address' => $addressInfo['address']
        ], JSON_UNESCAPED_UNICODE);

        Db::startTrans();
        try {
            Db::name('user_lottery_of_objects')->where(['id'=>$lottery_id])->update(['status' => 1, 'update_time' => $current_time]);
            $order_id = Db::name('mall_order')->insertGetId($orderArr);
            $orderArr['id'] = $order_id;
            Db::name('mall_order_item')->insert([
                'order_id' => $order_id,
                'goods_id' => $reward['goods_id'],
                'num' => 1,
                'sku' => '若无备注则随机',
                'price' => $goods['price'],
                'create_time' => $current_time,
                'update_time' => $current_time,
            ]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->miss($e->getMessage());
        }
        return $this->pass('领取成功');
    }
}
